/*
 * @Author: Drc
 * @Date: 2021-05-19 17:20:12
 * @LastEditTime: 2021-10-12 10:19:48
 * @LastEditors: Drc
 */

import React, {memo} from 'react'
import {View, Text, Platform, TextInput, TouchableOpacity, ActivityIndicator} from 'react-native'
import Pop, {PopProps} from './index'
import Theme from '@path/config/theme'
import {px2dp} from '@path/config/system'
import store from '@path/redux'
import Locale from '@path/locale'
import _ from 'lodash'
import {ThemeText} from '../ThemeComponents'

interface EmailAuthPopProps extends PopProps {
  length?: number
  onConfirm: (code: string) => any
  title: string
  toEmail?: string
  send: () => Promise<any>
  count?: number
  isAutoSendCode?: boolean
}

class EmailAuthPop extends Pop<EmailAuthPopProps> {
  constructor(props: any) {
    super(props)
  }

  static defaultProps: EmailAuthPopProps = {
    length: 6,
    count: 60,
    animationIn: 'zoomIn',
    animationOut: 'zoomOut',
  }

  countTimer?: NodeJS.Timeout

  state = {
    code: '',
    isLoading: false,
    count: 0,
  }

  onModalShow = () => {
    this.props.isAutoSendCode && this.send()
  }

  onClose = () => {
    this.setState({
      code: '',
    })
  }

  componentDidMount() {}

  componentWillUnmount() {
    this._stopCountDown()
  }

  componentDidUpdate() {
    if (this.state.code?.length === this.props.length) {
      typeof this.props.onConfirm === 'function' && this.props.onConfirm(this.state.code)
      this.setState({code: ''})
    }
  }

  send = () => {
    //请求中 || 未传入发送promise || 正在倒计时
    if (this.state.isLoading || typeof this.props.send !== 'function' || this.state.count > 0) {
      return
    }
    this.setState(
      {
        isLoading: true,
      },
      () => {
        this._stopCountDown()
        this.props
          .send()
          .then((res) => {
            this.showToast(res.msg)
            this.setState(
              {
                count: this.props.count,
              },
              () => {
                this._startCountDown()
              },
            )
          })
          .catch((err) => {
            this.showToast(err)
          })
          .finally(() => {
            this.setState({
              isLoading: false,
            })
          })
      },
    )
  }

  resetCountDown = () => {
    this.setState({
      count: 0,
    })
  }

  _startCountDown = () => {
    this.countTimer = setInterval(() => {
      this.setState({count: this.state.count - 1}, () => {
        if (this.state.count <= 0) {
          this._stopCountDown()
        }
      })
    }, 1000)
  }

  _stopCountDown = () => {
    if (this.countTimer) {
      clearInterval(this.countTimer)
      this.countTimer = undefined
    }
  }

  _renderInput = () => {
    const list = new Array(this.props.length).fill('')

    return (
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          flexWrap: 'nowrap',
          marginTop: px2dp(24),
        }}>
        {list.map((item, index) => {
          return (
            <View
              key={index}
              style={{
                flex: 1 / list.length,
                height: px2dp(38),
                marginLeft: index === 0 ? 0 : px2dp(10),
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: 8,
                backgroundColor: Theme.currentTheme === 'light' ? '#FCFCFC' : '#443F68',
                borderWidth: 1,
                borderColor: '#E0E0E0',
              }}>
              <ThemeText
                style={{
                  fontSize: 24,
                }}>
                {this.state.code[index]}
              </ThemeText>
            </View>
          )
        })}
        <TextInput
          autoFocus={Platform.OS === 'ios'}
          clearButtonMode={'never'}
          value={this.state.code}
          style={{
            opacity: 0,
            height: '100%',
            position: 'absolute',
            width: '100%',
          }}
          maxLength={this.props.length}
          onChangeText={(text) => {
            if (isNaN(Number(text))) {
              return
            }
            this.setState({
              code: text,
            })
          }}
          keyboardType={'number-pad'}
        />
      </View>
    )
  }

  renderContent = () => {
    return (
      <View
        style={{
          width: px2dp(327),
          backgroundColor: Theme.getThemeColor('bg'),
          borderRadius: 8,
          paddingVertical: px2dp(24),
          paddingHorizontal: px2dp(16),
          alignSelf: 'center',
        }}>
        {/* 标题 */}
        <ThemeText
          style={{
            fontSize: 15,
            color: Theme.getThemeColor('text_main'),
          }}>
          {this.props.title || Locale.getString('common.email_holder')}
        </ThemeText>
        {this.props.toEmail ? (
          <ThemeText style={{fontSize: 12, color: Theme.getThemeColor('text_tip'), marginTop: px2dp(5)}}>
            {Locale.getString('common.email_sent', {email: this.props.toEmail})}
          </ThemeText>
        ) : null}
        {/* 输入框 */}
        {this._renderInput()}
        {/* 重新发送 */}
        <TouchableOpacity
          style={{alignItems: 'flex-end', marginTop: px2dp(24), height: px2dp(20)}}
          activeOpacity={0.8}
          onPress={() => {
            this.send()
          }}
          disabled={this.state.isLoading || this.state.count > 0}>
          {this.state.isLoading ? (
            <ActivityIndicator animating color={Theme.getThemeColor('theme')} />
          ) : (
            <ThemeText style={{fontSize: 12, color: Theme.getThemeColor('theme')}}>
              {this.state.count > 0
                ? Locale.getString('common.send_counting', {num: `${this.state.count}`})
                : Locale.getString('action.resend')}
            </ThemeText>
          )}
        </TouchableOpacity>
      </View>
    )
  }
}

export default memo(EmailAuthPop, (prev, next) => _.isEqual(prev.isVisible, next.isVisible))
